<!-- src/views/stocktaking/task/taskList.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import { getStocktakingTaskPageApi, addStocktakingTaskApi, updateStocktakingTaskApi, deleteStocktakingTaskApi, executeTaskOnceApi } from '@/api/stocktaking/stocktakingTask.js'
import { getUserListApi } from '@/api/user.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import AddTask from './AddTask.vue'

// 搜索表单
const searchForm = ref({
  taskName: '',
  category: '',
  isEnable: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 用户列表
const userList = ref([])

// 控制添加任务弹窗显示
const addTaskDialogVisible = ref(false)

// 添加任务组件引用
const addTaskRef = ref(null)

// 盘点类型选项
const categoryOptions = [
  { label: '仓库盘点', value: 1 },
  { label: '库区盘点', value: 2 },
  { label: '库位盘点', value: 3 }
]

// 启用状态选项
const enableOptions = [
  { label: '启用', value: 1 },
  { label: '停用', value: 2 }
]

// 获取任务列表
const fetchTaskList = async () => {
  loading.value = true
  try {
    const res = await getStocktakingTaskPageApi(
      pagination.value.page,
      pagination.value.pageSize,
      searchForm.value.taskName,
      searchForm.value.category,
      searchForm.value.isEnable
    )
    tableData.value = res.data.rows
    pagination.value.total = res.data.total
  } catch (error) {
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserListApi()
    userList.value = res.data
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}

// 获取用户名
const getUserName = (userId) => {
  const user = userList.value.find(item => item.id == userId)
  return user ? user.name : '未知用户'
}

// 获取盘点类型标签
const getCategoryLabel = (category) => {
  const categoryMap = {
    1: '仓库盘点',
    2: '库区盘点',
    3: '库位盘点'
  }
  return categoryMap[category] || '未知类型'
}

// 获取启用状态标签
const getEnableStatusLabel = (isEnable) => {
  return isEnable === 1 ? '启用' : '停用'
}

// 处理搜索
const handleSearch = () => {
  pagination.value.page = 1
  fetchTaskList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    taskName: '',
    category: '',
    isEnable: ''
  }
  pagination.value.page = 1
  fetchTaskList()
}

// 分页变化
const handlePageChange = (page) => {
  pagination.value.page = page
  fetchTaskList()
}

// 添加任务按钮点击事件
const handleAddTask = () => {
  addTaskDialogVisible.value = true
}

// 关闭添加任务弹窗
const handleCloseAddTask = () => {
  addTaskDialogVisible.value = false
}

// 处理添加任务确认按钮
const handleConfirmAddTask = async (data) => {
  try {
    await ElMessageBox.confirm('确认要添加该盘点任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用后端接口
    await addStocktakingTaskApi(data)
    
    // 关闭弹窗
    handleCloseAddTask()
    
    // 刷新页面数据
    fetchTaskList()
    
    ElMessage.success('添加任务成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('添加任务失败: ' + error.message)
    }
  }
}

// 启用/停用任务
const toggleTaskStatus = async (row, status) => {
  try {
    const action = status === 1 ? '启用' : '停用'
    await ElMessageBox.confirm(`确认要${action}该任务吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 构造更新数据
    const updateData = {
      id: row.id,
      isEnable: status
    }
    
    // 调用后端接口更新状态
    await updateStocktakingTaskApi(updateData)
    
    // 更新本地数据
    row.isEnable = status
    
    ElMessage.success(`${action}任务成功`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}任务失败: ` + error.message)
    }
  }
}

// 删除任务
const deleteTask = async (row) => {
  try {
    await ElMessageBox.confirm('确认要删除该任务吗？删除后将无法恢复', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用后端接口删除任务
    await deleteStocktakingTaskApi(row.id)
    
    // 刷新页面数据
    fetchTaskList()
    
    ElMessage.success('删除任务成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除任务失败: ' + error.message)
    }
  }
}

// 执行一次任务
const executeTaskOnce = async (row) => {
  try {
    await ElMessageBox.confirm('确认要立即执行该任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用后端接口执行任务
    await executeTaskOnceApi(row.id)
    
    ElMessage.success('任务已开始执行')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('执行任务失败: ' + error.message)
    }
  }
}

// 初始化
onMounted(() => {
  fetchTaskList()
  fetchUserList()
})
</script>

<template>
  <div class="task-list-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <!-- 添加任务按钮放在最左边 -->
        <div class="left-section">
          <el-button type="primary" icon="Plus" @click="handleAddTask">添加任务</el-button>
        </div>
        
        <!-- 搜索条件放在最右边 -->
        <div class="right-section">
          <el-form-item label="任务名称">
            <el-input 
              v-model="searchForm.taskName" 
              placeholder="请输入任务名称" 
              clearable 
              style="width: 180px;"
            />
          </el-form-item>
          
          <el-form-item label="盘点类型">
            <el-select 
              v-model="searchForm.category" 
              placeholder="请选择盘点类型" 
              clearable 
              style="width: 120px;"
            >
              <el-option 
                v-for="item in categoryOptions" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value" 
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.isEnable" 
              placeholder="请选择状态" 
              clearable 
              style="width: 120px;"
            >
              <el-option 
                v-for="item in enableOptions" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value" 
              />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearch">查询</el-button>
            <el-button icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    
    <!-- 任务列表表格 -->
    <el-table 
      :data="tableData" 
      v-loading="loading" 
      border 
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="taskName" label="任务名称" min-width="120" />
      <el-table-column prop="cronExpression" label="cron表达式" min-width="150" />
      <el-table-column prop="startTime" label="开始时间" min-width="160" />
      <el-table-column label="盘点类型" width="100">
        <template #default="scope">
          {{ getCategoryLabel(scope.row.category) }}
        </template>
      </el-table-column>
      <el-table-column prop="targetName" label="目标名称" min-width="120" />
      <el-table-column label="操作员工" width="100">
        <template #default="scope">
          {{ getUserName(scope.row.empId) }}
        </template>
      </el-table-column>
      <el-table-column label="是否启用" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isEnable === 1 ? 'success' : 'info'">
            {{ getEnableStatusLabel(scope.row.isEnable) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="160" />
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="scope">
          <el-button 
            size="small" 
            :type="scope.row.isEnable === 1 ? 'warning' : 'success'"
            @click="toggleTaskStatus(scope.row, scope.row.isEnable === 1 ? 2 : 1)"
          >
            {{ scope.row.isEnable === 1 ? '停用' : '启用' }}
          </el-button>
          <el-button size="small" type="primary" @click="executeTaskOnce(scope.row)">执行一次</el-button>
          <el-button size="small" type="danger" @click="deleteTask(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <el-pagination
      layout="total, prev, pager, next, jumper"
      :current-page="pagination.page"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      @current-change="handlePageChange"
      style="margin-top: 20px; text-align: right;"
    />
    
    <!-- 添加任务弹窗 -->
    <AddTask
      v-model:visible="addTaskDialogVisible"
      ref="addTaskRef"
      @confirm="handleConfirmAddTask"
    />
  </div>
</template>

<style scoped>
.task-list-container {
  padding: 20px;
  background-color: #fff;
}

.search-bar {
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.search-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.left-section {
  flex-shrink: 0;
}

.right-section {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  justify-content: flex-end;
  flex: 1;
}
</style>